package com.aaa.vegetablemarketexpress.service.impl;

import com.aaa.vegetablemarketexpress.dao.NoticeDao;
import com.aaa.vegetablemarketexpress.entity.Notice;
import com.aaa.vegetablemarketexpress.entity.User;
import com.aaa.vegetablemarketexpress.service.NoticeService;
import com.aaa.vegetablemarketexpress.util.CustomException;
import com.aaa.vegetablemarketexpress.util.Page;
import com.aaa.vegetablemarketexpress.util.ResultStatus;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

/**
 * @FileName: NoticeServiceImpl
 * @Description:
 * @Author: 张钰哲
 * @CreateTime: 2025/9/13 15:18
 * @Version: 1.0.0
 */
@Service
public class NoticeServiceImpl implements NoticeService {
    @Resource
    private NoticeDao noticeDao;
    @Resource
    private HttpSession session;
    @Override
    public Notice getNoticeById(Long noticeId) {
        return noticeDao.selectNoticeById(noticeId);
    }

    @Override
    public PageInfo<Notice> queryByPage(Page<Notice> page) {
        Integer pageNo = page.getPageNo();
        Integer pageSize = page.getPageSize();
        if (pageNo == null || pageSize == null||pageNo == 0||pageSize == 0) {
            throw new CustomException(ResultStatus.PARAM_ISNULL.getStatusCode(), ResultStatus.PARAM_ISNULL.getStatusMsg());
        }
        PageHelper.startPage(pageNo, pageSize);
        Notice data = page.getData();
        List<Notice> noticeList = noticeDao.selectNoticeList(data);
        return new PageInfo<>(noticeList);
    }

    @Override
    public int addNotice(Notice notice) {
        User userInfo = (User) session.getAttribute("userInfo");
        notice.setCreateBy(userInfo.getUserName());
        notice.setCreateTime(new Date());
        return noticeDao.insertNotice(notice);
    }

    @Override
    public int updateNotice(Notice notice) {
        User userInfo = (User) session.getAttribute("userInfo");
        notice.setUpdateBy(userInfo.getUserName());
        notice.setUpdateTime(new Date());
        return noticeDao.updateNotice(notice);
    }

    @Override
    public int deleteNoticeById(Long noticeId) {
        return noticeDao.deleteNoticeById(noticeId);
    }
    @Override
    public Notice view(Long noticeId) {
        Notice n = noticeDao.selectById(noticeId);
        if (n == null || !"0".equals(n.getStatus())) {
            throw new CustomException(ResultStatus.PARAM_ISNULL.getStatusCode(), ResultStatus.PARAM_ISNULL.getStatusMsg());
        }
        noticeDao.incrViewCount(noticeId);
        // 重新查一次，返回最新浏览量
        return noticeDao.selectById(noticeId);
    }
}
